package com.punai.standard.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.punai.common.core.domain.TreeBo;
import com.punai.common.core.domain.entity.SysDictData;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.utils.DictUtils;
import com.punai.common.utils.PageUtils;
import com.punai.common.utils.ParseContentUtil;
import com.punai.standard.domain.StaGxChapter;
import com.punai.standard.domain.StaGxFee;
import com.punai.standard.domain.StaVersion;
import com.punai.standard.domain.constants.StaConstants;
import com.punai.standard.domain.vo.StaFeeVo;
import com.punai.standard.domain.vo.StaSimplifyVo;
import com.punai.standard.mapper.*;
import com.punai.standard.service.IStaGxChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工序章节Service业务层处理
 *
 * @author zxw
 * @date 2022-12-13
 */
@Service
public class StaGxChapterServiceImpl extends ServiceImpl<StaGxChapterMapper,StaGxChapter> implements IStaGxChapterService
{
    @Autowired
    private StaGxChapterMapper staGxChapterMapper;
    @Autowired
    private StaGxFeeMapper staGxFeeMapper;
    @Autowired
    private StaLinkFeatureMapper staLinkFeatureMapper;
    @Autowired
    private StaLinkGxfeeCategoryMapper staLinkGxfeeCategoryMapper;
    @Autowired
    private StaSubpkLinkConsumeMapper consumeMapper;
    @Autowired
    private StaVersionMapper staVersionMapper;

    /**
     * 查询工序章节
     *
     * @param id 工序章节主键
     * @return 工序章节
     */
    @Override
    public StaGxChapter selectStaGxChapterById(String id)
    {
        return staGxChapterMapper.selectStaGxChapterById(null,id);
    }

    /**
     * 查询工序章节列表
     *
     * @param staGxChapter 工序章节
     * @return 工序章节
     */
    @Override
    public List<StaGxChapter> selectStaGxChapterList(StaGxChapter staGxChapter)
    {
        return staGxChapterMapper.selectStaGxChapterList(staGxChapter);
    }

    /**
     * 新增工序章节
     *
     * @param staGxChapter 工序章节
     * @return 结果
     */
    @Override
    public int insertStaGxChapter(StaGxChapter staGxChapter)
    {
            return staGxChapterMapper.insert(staGxChapter);
    }

    /**
     * 修改工序章节
     *
     * @param staGxChapter 工序章节
     * @return 结果
     */
    @Override
    public int updateStaGxChapter(StaGxChapter staGxChapter)
    {
        return staGxChapterMapper.updateById(staGxChapter);
    }

    /**
     * 批量删除工序章节
     *
     * @param ids 需要删除的工序章节主键
     * @return 结果
     */
    @Override
    public int deleteStaGxChapterByIds(String[] ids)
    {
        return staGxChapterMapper.deleteStaGxChapterByIds(ids);
    }

    /**
     * 删除工序章节信息
     *
     * @param id 工序章节主键
     * @return 结果
     */
    @Override
    public int deleteStaGxChapterById(String id)
    {
        return staGxChapterMapper.deleteStaGxChapterById(id);
    }

    @Override
    public List<TreeBo> treeData(String versionId,Long companyId) {
        // 2023-02-23 修改，
        // 旧版：选择版本查看数据  --> 新版：直接查询最新版数据
        // 拿最新版
//        List<String> strings = staVersionMapper.selectIdByType(companyId, StaConstants.GX_TYPE);

        // 2023-03-17 修改，
        // 旧版：直接查询最新版数据  --> 新版：选择版本查看数据
        List<StaGxChapter> staGxChapters = staGxChapterMapper.selectList(
                Wrappers.<StaGxChapter>lambdaQuery()
                        .eq(StaGxChapter::getVersionId, versionId)
        );

        List<TreeBo> result = new ArrayList<>();
        if (CollUtil.isEmpty(staGxChapters)) {
            return result;
        }
        result = TreeBo.convert(staGxChapters).get(0).getChildren();
        return result;
    }

    @Override
    public List<String> getSpecialtyList(Long companyId) {
        List<String> versionSpecialty = new ArrayList<>();

        List<String> specIds = staVersionMapper.selectSpecByType(companyId, StaConstants.GX_TYPE);
        if(CollUtil.isNotEmpty(specIds)){
            List<SysDictData> fee_projecttype = DictUtils.getDictCache("fee_projecttype");
            for (SysDictData sysDictData : fee_projecttype) {
                if(specIds.contains(sysDictData.getDictValue())){
                    versionSpecialty.add(sysDictData.getDictValue());
                }
            }
        }
        return versionSpecialty;
    }

    @Override
    public List<StaVersion> getVersionListBySpecId(Long companyId,String topId) {
        return staVersionMapper.selectListBySpecId(companyId,StaConstants.GX_TYPE, topId);
    }

    @Override
    public TableDataInfo feeList(StaFeeVo vo, Long companyId) {
        String chapterId = vo.getChapterId();
        String versionId = vo.getVersionId();

        List<String> chapterIds = new ArrayList<>();
        chapterIds.add(0,chapterId);

        PageUtils.startPage();
        List<StaGxFee> staGxFees = staGxFeeMapper.selectStaGxFeeList(vo,versionId,chapterIds);
        if (CollUtil.isEmpty(staGxFees)) {
            return new TableDataInfo(staGxFees,0);
        }
        Long total = new PageInfo(staGxFees).getTotal();

        for (StaGxFee staGxFee : staGxFees) {
            String content = staGxFee.getContent();
            staGxFee.setContent(ParseContentUtil.parseContent(content));

            // 设置材机耗量
            // 2023-05-17 修改为动态获取 所以屏蔽
//            staGxFee.setCjCategoryBos(consumeMapper.selectSubpkConsume(staGxFee.getId(),versionId,address,companyId));
        }
        // 获取特征
        List<String> gxIds = staGxFees.stream().map(StaGxFee::getId).collect(Collectors.toList());
        List<StaSimplifyVo> itemIdFeatureNameList = staLinkFeatureMapper.selectFeatureBoGx(gxIds, versionId, companyId);
        Map<String, String> itemIdFeatureNameMap = itemIdFeatureNameList.stream().collect(Collectors.toMap(StaSimplifyVo::getId, StaSimplifyVo::getName));
        staGxFees.forEach(e -> e.setFeatureValues(itemIdFeatureNameMap.get(e.getId())));
        // 获取工序
//        List<CJCategoryBo> cjCategoryBos = staLinkGxfeeCategoryMapper.selectCategoryBo(gxIds,versionId,companyId);
//        if (CollUtil.isNotEmpty(cjCategoryBos)) {
//            // 获取
//            List<StaSubpkLinkConsume> staSubpkLinkConsumes = consumeMapper.selectList(
//                    Wrappers.<StaSubpkLinkConsume>lambdaQuery()
//                            .eq(StaSubpkLinkConsume::getVersionId, versionId)
//                            .in(StaSubpkLinkConsume::getSubpkItemId, gxIds)
//            );
//            Map<String, List<StaSubpkLinkConsume>> collect = staSubpkLinkConsumes.stream().collect(Collectors.groupingBy(StaSubpkLinkConsume::getCategoriesId));


//            if(CollUtil.isNotEmpty(collect)) {
//                Map<String, List<Map<String, Object>>> cjMap = cjCategoryBos.stream().collect(Collectors.groupingBy(stringObjectMap -> Convert.toStr(stringObjectMap.get("itemId"))));
//                for (StaGxFee staGxFee : staGxFees) {
//                    String feeId = staGxFee.getId();
//                    List<Map<String, Object>> categoryBos = cjMap.get(feeId);
//                    if (CollUtil.isNotEmpty(categoryBos)) {
//                        for (Map<String, Object> categoryBo : categoryBos) {
//                            String id = Convert.toStr(categoryBo.get("id"));
//                            List<StaSubpkLinkConsume> staConsumes = collect.get(id);
//                            List<StaSubpkLinkConsume> filterStaConsumes = staConsumes.stream().filter(staSubpkLinkConsume -> StringUtils.equals(staSubpkLinkConsume.getSubpkItemId(), staGxFee.getId())).collect(Collectors.toList());
//                            if (CollUtil.isNotEmpty(filterStaConsumes)) {
//                                StaSubpkLinkConsume staConsume = filterStaConsumes.get(0);
//                                categoryBo.put("consumption", staConsume.getReferenceConsume());
//                                for (StaSubpkLinkConsume staSubpkLinkConsume : filterStaConsumes) {
//                                    categoryBo.put(StaConstants.REALITY_CONSUME_NAME + staSubpkLinkConsume.getAddress(), staSubpkLinkConsume.getRealityConsume().toString());
//                                }
//                            }
//                        }
//                    }
//                    staGxFee.setCjCategoryBos(categoryBos);
//                }
//            }
//        }
        return new TableDataInfo(staGxFees,total.intValue());
    }

    @Override
    public List<String> selectAddressByVersionId(String versionId) {
        return staGxChapterMapper.selectAddressByVersionId(versionId);
    }
}
